package com.fanben100.util;
import javax.crypto.*;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;

/**
 * Created by IntelliJ IDEA.
 * User: LEO
 * Date: 2005-11-30
 * Time: 11:19:23
  */
public class EncryptDecryptData{
    static String str = "南京金脉博通";
    public static void main(String[] args)  {
        System.out.println("明文");
        System.out.println(str);
        byte[] str1 = new byte[0];

        KeyGenerator keygen = null;
        SecretKey secretkey = null;
        try {
            str1 = str.getBytes("UTF-8");
            keygen = KeyGenerator.getInstance("DESede");
            keygen.init(168);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        secretkey = keygen.generateKey();
        byte[] kb = secretkey.getEncoded();
        int i=0;
        System.out.println("密钥");
        for(i=0;i<kb.length;i++)
        {
            System.out.print(kb[i]+",");
        }
        Cipher cipher = null;
        byte[] encrypted = new byte[0];
        try {
            cipher = Cipher.getInstance("DESede");
            cipher.init(Cipher.ENCRYPT_MODE,secretkey);
            encrypted = cipher.doFinal(str1);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        System.out.println();
        System.out.println("密文");
        for(i=0;i<encrypted.length;i++)
        {
            System.out.print(encrypted[i]+",");
        }
        byte[] decrypted = new byte[0];
        try {
            cipher.init(Cipher.DECRYPT_MODE,secretkey);
            decrypted = cipher.doFinal(encrypted);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        String str2 = new String(decrypted);
        System.out.println("解密后的原文");
        System.out.println(str2);
    }
    

}